var express = require('express');
var router = express.Router();
//引入数据库包
var db = require("./db.js");
var md5=require("md5")


/**
 * 查询列表页
 */
router.get('/', function (req, res, next) {

    db.query('select * from person', function (err, rows) {
        console.log(rows);
        if (err) {
            res.render('persons', {title: 'nodeJsDemo', datas: []});
        } else {
            res.render('persons', {title: 'nodeJsDemo', datas: rows});
        }
    })
});
/**
 * 新增页面跳转
 */

router.get('/add', function (req, res) {
    res.render('add');
});
router.post('/add', function (req, res) {
    var username = req.body.username;
    var age = req.body.age;
    var password = req.body.password;
    var pass=md5(password)

    db.query("insert into person(username,age,password) values('" + username + "'," + age + ",'" + pass + "')", function (err, rows) {
        if (err) {
            /* res.send和res.end的区别  http://blog.csdn.net/genziisme/article/details/70144334*/
            res.send("错了傻吊:"+err)
        } else {
            res.redirect('/persons');
        }
    })
});

/**
 * 删
 */
router.get('/del/:id', function (req, res) {
    var id = req.params.id;
    db.query("delete from person where id=" + id, function (err, rows) {
        if (err) {
            res.send("没删除掉："+err)
        } else {
            res.redirect('/persons')
        }
    });
});
/**
 * 修改
 */
router.get('/toUpdate/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    db.query("select * from person where id=" + id, function (err, rows) {
        if (err) {
            res.send("修改跳转失败"+err)
        } else {
            res.render("update", {datas: rows});       //直接跳转
        }
    });
});
router.post('/update', function (req, res) {
    var id = req.body.id;
    var username = req.body.username;
    var password = req.body.password;
    var  pass=md5(password)
    var age = req.body.age;

    db.query("update person set username='" + username + "',age='" + age + "',password='"+pass+"' where id=" + id, function (err, rows) {
        if (err) {
            res.send("修改失败了哈哈哈："+err)
        } else {
            res.redirect('/persons');
        }
    });
});
/**
 * 查询
 */
router.post('/search', function (req, res) {
    var username = req.body.s_username;
    var age = req.body.s_age;
    var sql = "select * from person";
    if (username) {
        sql += " and username like '%" + username + "%' ";
    }
    if (age) {

        sql += " and age=" + age + " ";
    }

    sql = sql.replace("and","where");
    db.query(sql, function (err, rows) {
        if (err) {
            res.end("查询失败：", err)
        } else {
            res.render("persons", {title: 'nodeJsDemo', datas: rows, s_username: username, s_age: age});
        }
    });
});


module.exports = router;